// 导入uni-id-common模块和数据库
// 使用相对路径引用uni_modules中的模块
const uniID = require('../../../../uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js');
const db = uniCloud.database();
const _ = db.command;
// 导入配置中心
const createConfigCenter = require('../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js');

/**
 * 获取评论列表
 * @param {Object} event 客户端传入的参数
 * @param {String} event.token 用户token
 * @param {String} event.postId 动态ID
 * @param {Number} event.pageNum 页码，默认为1
 * @param {Number} event.pageSize 每页数量，默认为10
 * @param {String} event.orderType 排序类型：time(按时间)/like(按点赞数)
 * @param {Object} context 上下文信息
 */
exports.main = async (event, context) => {
  const { token, postId, pageNum = 1, pageSize = 10, orderType = 'time' } = event;
  
  // 初始化配置中心并获取uni-id配置
  const config = createConfigCenter({ pluginId: 'uni-id' });
  const uniIdConfig = config.config();
  
  // 初始化uniID实例
  const uniIDIns = uniID.createInstance({
    context,
    config: uniIdConfig
  });
  
  // 解析页码和每页数量
  const page = parseInt(pageNum) || 1;
  const size = parseInt(pageSize) || 10;
  const skip = (page - 1) * size;
  
  // 校验参数
  if (!postId) {
    return {
      code: 1,
      message: '动态ID不能为空'
    };
  }
  
  // 检查并验证token
  let currentUserId = null;
  if (token) {
    try {
      const checkTokenRes = await uniIDIns.checkToken(token);
      if (!checkTokenRes.code) {
        currentUserId = checkTokenRes.uid;
      }
    } catch (error) {
      console.error('token验证失败:', error);
    }
  }
  
  try {
    // 检查帖子是否存在并验证权限
    const postRes = await db.collection('dynamic_posts').doc(postId).get();
    
    if (!postRes.data) {
      return {
        code: 1,
        message: '动态不存在'
      };
    }
    
    const post = postRes.data;
    
    // 检查权限
    if (post.privacy === 'private' && post.userId !== currentUserId) {
      // 检查是否是关注者
      if (currentUserId) {
        const followRes = await db.collection('user_follows')
          .where({
            userId: currentUserId,
            followId: post.userId
          })
          .count();
        
        if (followRes.total === 0) {
          return {
            code: 1,
            message: '无权限查看此动态的评论'
          };
        }
      } else {
        return {
          code: 1,
          message: '请先登录'
        };
      }
    } else if (post.privacy === 'followers' && post.userId !== currentUserId) {
      // 检查是否是关注者
      if (currentUserId) {
        const followRes = await db.collection('user_follows')
          .where({
            userId: currentUserId,
            followId: post.userId
          })
          .count();
        
        if (followRes.total === 0) {
          return {
            code: 1,
            message: '无权限查看此动态的评论'
          };
        }
      } else {
        return {
          code: 1,
          message: '请先登录'
        };
      }
    }
    
    // 查询评论列表
    const commentsCollection = db.collection('comments');
    let query = {
      postId: postId,
      parentId: _.eq(null)
    };
    
    // 排序方式
    let orderByField = 'createTime';
    let orderByDirection = 'desc';
    
    if (orderType === 'like') {
      orderByField = 'likeCount';
    }
    
    // 查询总数
    const totalRes = await commentsCollection.where(query).count();
    const total = totalRes.total;
    
    // 查询分页数据
    const commentsRes = await commentsCollection
      .where(query)
      .orderBy(orderByField, orderByDirection)
      .skip(skip)
      .limit(size)
      .get();
    
    let comments = commentsRes.data;
    
    // 如果用户已登录，检查用户是否点赞了这些评论
    if (currentUserId && comments.length > 0) {
      const commentIds = comments.map(comment => comment._id);
      
      // 查询用户点赞记录
      const likesRes = await db.collection('comment_likes')
        .where({
          userId: currentUserId,
          commentId: _.in(commentIds)
        })
        .get();
      
      // 构建已点赞的评论ID集合
      const likedCommentIds = new Set(likesRes.data.map(like => like.commentId));
      
      // 更新评论的点赞状态
      comments = comments.map(comment => ({
        ...comment,
        isLiked: likedCommentIds.has(comment._id)
      }));
    }
    
    // 查询每条评论的回复
    if (comments.length > 0) {
      for (let i = 0; i < comments.length; i++) {
        const comment = comments[i];
        
        // 查询前3条回复
        const repliesRes = await commentsCollection
          .where({
            postId: postId,
            parentId: comment._id
          })
          .orderBy('createTime', 'asc')
          .limit(3)
          .get();
        
        let replies = repliesRes.data;
        
        // 检查回复的点赞状态
        if (currentUserId && replies.length > 0) {
          const replyIds = replies.map(reply => reply._id);
          
          const replyLikesRes = await db.collection('comment_likes')
            .where({
              userId: currentUserId,
              commentId: _.in(replyIds)
            })
            .get();
          
          const likedReplyIds = new Set(replyLikesRes.data.map(like => like.commentId));
          
          replies = replies.map(reply => ({
            ...reply,
            isLiked: likedReplyIds.has(reply._id)
          }));
        }
        
        comment.replies = replies;
      }
    }
    
    return {
      code: 0,
      message: '获取评论列表成功',
      data: comments,
      total: total,
      page: page,
      pageSize: size
    };
  } catch (error) {
    console.error('获取评论列表失败:', error);
    return {
      code: 1,
      message: '获取评论列表失败',
      data: error.message
    };
  }
};